<template>
  <div class="app-wrapper">
    <!-- 移动端菜单按钮 -->
    <button
      class="mobile-menu-btn hidden-desktop"
      @click="toggleMobileSidebar"
      style="display: none;"
    >
      <el-icon><Menu /></el-icon>
    </button>

    <!-- 侧边栏 -->
    <div class="sidebar-container" :class="{ 'mobile-open': mobileSidebarOpen }">
      <div class="logo-container">
        <img src="/images/logo.png" alt="哈喽啤鲜生" class="logo-image" />
        <h1 class="logo-title">哈喽啤鲜生</h1>
        <p class="logo-subtitle">国贸店</p>
      </div>
      
      <el-menu
        :default-active="activeMenu"
        class="sidebar-menu"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
        router
      >
        <el-menu-item index="/pos">
          <el-icon><Goods /></el-icon>
          <span>收银系统</span>
        </el-menu-item>
        
        <el-menu-item index="/products">
          <el-icon><List /></el-icon>
          <span>商品管理</span>
        </el-menu-item>
        
        <el-menu-item index="/orders">
          <el-icon><Document /></el-icon>
          <span>订单管理</span>
        </el-menu-item>
        
        <el-menu-item index="/shifts">
          <el-icon><Timer /></el-icon>
          <span>日报管理</span>
        </el-menu-item>
        
        <el-menu-item index="/settings">
          <el-icon><Setting /></el-icon>
          <span>系统设置</span>
        </el-menu-item>
      </el-menu>
      
      <!-- 时间显示 -->
      <div class="sidebar-footer">
        <div class="datetime">
          <div class="date">{{ currentDate }}</div>
          <div class="time">{{ currentTime }}</div>
        </div>
      </div>
    </div>
    
    <!-- 主要内容区 -->
    <div class="main-container">
      <!-- 顶部导航栏 -->
      <div class="navbar">
        <div class="left">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>{{ pageTitle }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <div class="right">
          <!-- 添加管理页面导航入口 -->
          <el-button type="primary" size="small" @click="goToAdmin" class="admin-btn">
            <el-icon><Monitor /></el-icon>
            <span>管理后台</span>
          </el-button>
          
          <el-dropdown trigger="click" @command="handleCommand">
            <span class="user-dropdown-link">
              {{ userName }}
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      
      <!-- 内容区域 -->
      <div class="app-main">
        <router-view />
      </div>
    </div>
    
    <!-- 个人信息弹窗 -->
    <el-dialog
      v-model="showProfileDialog"
      title="个人信息"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="profileFormRef" 
        :model="profileForm" 
        :rules="profileRules" 
        label-width="100px"
        class="profile-form"
      >
        <el-form-item label="用户名">
          <el-input v-model="profileForm.username" disabled />
        </el-form-item>
        
        <el-form-item label="姓名" prop="name">
          <el-input v-model="profileForm.name" />
        </el-form-item>
        
        <el-form-item label="角色">
          <el-tag :type="getRoleTagType(profileForm.role)">
            {{ getRoleLabel(profileForm.role) }}
          </el-tag>
        </el-form-item>
        
        <el-form-item label="电话" prop="phone">
          <el-input v-model="profileForm.phone" />
        </el-form-item>
        
        <el-divider content-position="center">修改密码（可选）</el-divider>
        
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input 
            v-model="profileForm.oldPassword" 
            type="password" 
            placeholder="留空则不修改密码"
            show-password 
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="profileForm.newPassword" 
            type="password" 
            placeholder="留空则不修改密码"
            show-password 
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="profileForm.confirmPassword" 
            type="password" 
            placeholder="留空则不修改密码"
            show-password 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleProfileCancel">取消</el-button>
          <el-button type="primary" @click="handleProfileSubmit" :loading="profileSubmitting">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted, reactive, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Goods, List, Document, Timer, Setting, ArrowDown, Monitor, Menu } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import api from '@/utils/api'

const route = useRoute()
const router = useRouter()

// 当前用户信息
const userName = ref('用户')
const userRole = ref('')

// 移动端侧边栏状态
const mobileSidebarOpen = ref(false)

// 时间相关
const currentDate = ref('')
const currentTime = ref('')
let timer = null

const updateTime = () => {
  const now = new Date()
  currentDate.value = now.toLocaleDateString()
  currentTime.value = now.toLocaleTimeString()
}

// 获取当前用户信息
const getUserInfo = async () => {
  try {
    const userStr = localStorage.getItem('user')
    if (userStr) {
      const user = JSON.parse(userStr)
      userName.value = user.name || user.username || '用户'
      userRole.value = user.role || ''
      
      // 从服务器获取最新用户信息
      try {
        const response = await api.get(`/users/${user.id}`)
        if (response.data && response.data.status === 'success') {
          const updatedUser = {
            ...user,
            ...response.data.data,
            role: response.data.data.role
          }
          
          // 更新本地存储和显示
          localStorage.setItem('user', JSON.stringify(updatedUser))
          userName.value = updatedUser.name || updatedUser.username || '用户'
          userRole.value = updatedUser.role || ''
          
          console.log('前台用户信息已更新:', updatedUser)
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    }
  } catch (e) {
    console.error('解析用户信息失败:', e)
  }
}

// 计算当前活动菜单
const activeMenu = computed(() => route.path)

// 计算当前页面标题
const pageTitle = computed(() => route.meta?.title || '首页')

// 判断是否为管理员用户 - 暂时始终返回true，允许所有用户访问管理后台
const isAdmin = computed(() => true)

// 跳转到管理后台
const goToAdmin = () => {
  router.push('/admin/dashboard')
}

// 切换移动端侧边栏
const toggleMobileSidebar = () => {
  mobileSidebarOpen.value = !mobileSidebarOpen.value
}

// 监听窗口大小变化
const handleResize = () => {
  if (window.innerWidth > 768) {
    mobileSidebarOpen.value = false
  }
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'logout') {
    ElMessageBox.confirm('确定要退出登录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 清除登录信息
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      
      // 跳转到登录页
      router.push('/login')
    }).catch(() => {})
  } else if (command === 'profile') {
    // 显示个人信息弹窗
    showProfileDialog.value = true
  }
}

// 个人信息弹窗显示状态
const showProfileDialog = ref(false)

// 个人信息表单
const profileForm = reactive({
  id: '',
  username: '',
  name: '',
  role: '',
  phone: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 个人信息表单验证规则
const profileRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  newPassword: [
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { 
      validator: (rule, value, callback) => {
        if (profileForm.newPassword && value !== profileForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  oldPassword: [
    { 
      validator: (rule, value, callback) => {
        if (profileForm.newPassword && !value) {
          callback(new Error('修改密码时需要输入旧密码'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 个人信息表单引用
const profileFormRef = ref(null)
const profileSubmitting = ref(false)

// 获取用户角色标签类型
const getRoleTagType = (role) => {
  const types = {
    admin: 'danger',
    manager: 'warning',
    cashier: 'primary'
  }
  return types[role] || 'info'
}

// 获取用户角色显示名称
const getRoleLabel = (role) => {
  const labels = {
    admin: '管理员',
    manager: '经理',
    cashier: '收银员'
  }
  return labels[role] || '未知角色'
}

// 获取个人信息
const getProfileInfo = async () => {
  try {
    const userStr = localStorage.getItem('user')
    if (userStr) {
      const user = JSON.parse(userStr)
      
      // 获取最新用户信息
      const response = await api.get(`/users/${user.id}`)
      
      if (response.data && response.data.status === 'success') {
        const userData = response.data.data
        
        // 更新表单数据
        profileForm.id = userData.id
        profileForm.username = userData.username
        profileForm.name = userData.name || ''
        profileForm.role = userData.role
        profileForm.phone = userData.phone || ''
        
        // 清空密码字段
        profileForm.oldPassword = ''
        profileForm.newPassword = ''
        profileForm.confirmPassword = ''
      } else {
        ElMessage.error('获取用户信息失败: ' + (response.data?.message || '未知错误'))
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 提交个人信息表单
const handleProfileSubmit = async () => {
  if (!profileFormRef.value) return
  
  profileFormRef.value.validate(async (valid) => {
    if (valid) {
      profileSubmitting.value = true
      
      try {
        // 准备提交数据
        const updateData = {
          name: profileForm.name,
          phone: profileForm.phone
        }
        
        // 如果填写了密码，则添加密码相关字段
        if (profileForm.newPassword) {
          updateData.oldPassword = profileForm.oldPassword
          updateData.password = profileForm.newPassword
        }
        
        // 发送更新请求
        const response = await api.put(`/users/${profileForm.id}/profile`, updateData)
        
        if (response.data && response.data.status === 'success') {
          ElMessage.success('个人信息更新成功')
          
          // 更新本地存储的用户信息
          const userStr = localStorage.getItem('user')
          if (userStr) {
            const user = JSON.parse(userStr)
            localStorage.setItem('user', JSON.stringify({
              ...user,
              name: profileForm.name,
              phone: profileForm.phone
            }))
          }
          
          // 更新显示的用户名
          userName.value = profileForm.name || profileForm.username || '用户'
          
          // 关闭弹窗
          showProfileDialog.value = false
        } else {
          ElMessage.error('更新失败: ' + (response.data?.message || '未知错误'))
        }
      } catch (error) {
        console.error('更新个人信息失败:', error)
        ElMessage.error('更新个人信息失败')
      } finally {
        profileSubmitting.value = false
      }
    }
  })
}

// 关闭个人信息弹窗
const handleProfileCancel = () => {
  showProfileDialog.value = false
}

// 监听弹窗打开，获取个人信息
watch(showProfileDialog, (newVal) => {
  if (newVal) {
    getProfileInfo()
  }
})

// 组件挂载时获取用户信息
onMounted(() => {
  getUserInfo()
  updateTime() // 启动时间更新
  timer = setInterval(updateTime, 1000) // 每秒更新一次时间

  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }

  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.app-wrapper {
  position: relative;
  height: 100vh;
  width: 100%;
  display: flex;
}

/* 侧边栏样式 */
.sidebar-container {
  width: 210px;
  height: 100%;
  background: #2c3e50;
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  overflow-y: auto;
  box-shadow: none;
  z-index: 1001;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
}

/* 移动端菜单按钮 */
.mobile-menu-btn {
  display: none;
  position: fixed;
  top: 10px;
  left: 10px;
  z-index: 1500;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px;
  font-size: 18px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.logo-container {
  height: auto;
  padding: 15px 0;
  text-align: center;
  color: #fff;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  margin-bottom: 5px;
  background: #263445;
}

.logo-image {
  width: 60px;
  height: 60px;
  margin-bottom: 5px;
  border-radius: 5px;
}

.logo-title {
  font-size: 16px;
  margin: 5px 0 0;
  font-weight: bold;
}

.logo-subtitle {
  font-size: 12px;
  margin: 5px 0 0;
  opacity: 0.8;
  background: rgba(255, 255, 255, 0.1);
  display: inline-block;
  padding: 1px 6px;
  border-radius: 8px;
  max-width: 80%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.sidebar-menu {
  border-right: none;
  padding: 5px 0;
}

:deep(.el-menu) {
  border-right: none !important;
  background-color: transparent !important;
}

:deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
  margin: 2px 0;
  padding: 0 15px !important;
  border-left: 2px solid transparent;
  position: relative;
  z-index: 1;
}

:deep(.el-menu-item.is-active) {
  background-color: #1f2d3d !important;
  border-left: 2px solid #409EFF;
  position: relative;
  z-index: 2;
}

:deep(.el-menu-item:hover) {
  background-color: #1f2d3d !important;
}

:deep(.el-menu-item .el-icon) {
  margin-right: 10px;
  font-size: 18px;
  vertical-align: middle;
  will-change: auto;
}

:deep(.el-menu-item span) {
  font-size: 14px;
}

/* 主内容区样式 */
.main-container {
  flex: 1;
  margin-left: 210px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  will-change: transform;
}

/* 顶部导航栏样式 */
.navbar {
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
  background: #fff;
  box-shadow: 0 1px 2px rgba(0, 21, 41, 0.08);
  position: relative;
  z-index: 1000;
}

.user-dropdown-link {
  cursor: pointer;
  color: #606266;
  display: flex;
  align-items: center;
  padding: 0 8px;
  height: 40px;
  border-radius: 4px;
}

.user-dropdown-link:hover {
  background-color: #f5f7fa;
}

/* 内容区域样式 */
.app-main {
  flex: 1;
  overflow: auto;
  padding: 15px;
  background-color: #f5f7f9;
  position: relative;
  will-change: transform;
  -webkit-overflow-scrolling: touch;
}

/* 管理按钮样式 */
.admin-btn {
  margin-right: 15px;
}

.right {
  display: flex;
  align-items: center;
}

.sidebar-footer {
  margin-top: auto;
  padding: 15px 0;
  text-align: center;
  color: #a7b1c2;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(0, 0, 0, 0.1);
}

.datetime {
  font-family: 'Arial', sans-serif;
}

.date {
  font-size: 14px;
  margin-bottom: 5px;
}

.time {
  font-size: 18px;
  font-weight: bold;
}

/* 响应式布局 */
@media (max-width: 1366px) and (min-width: 1025px) {
  .sidebar-container {
    width: 180px;
  }

  .main-container {
    margin-left: 180px;
  }
}

@media (max-width: 1024px) and (min-width: 769px) {
  .sidebar-container {
    width: 60px;
    overflow: visible;
  }

  .main-container {
    margin-left: 60px;
  }

  /* 隐藏侧边栏文字，只显示图标 */
  .sidebar-container .el-menu-item span,
  .logo-title,
  .logo-subtitle {
    display: none;
  }

  .logo-container {
    padding: 10px 5px;
  }

  .logo-image {
    width: 40px;
    height: 40px;
  }

  .sidebar-footer {
    display: none;
  }
}

@media (max-width: 768px) {
  .mobile-menu-btn {
    display: block !important;
  }

  .sidebar-container {
    transform: translateX(-100%);
    z-index: 2000;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
  }

  .sidebar-container.mobile-open {
    transform: translateX(0);
  }

  .main-container {
    margin-left: 0;
    width: 100%;
  }

  .navbar {
    padding-left: 50px; /* 为移动端菜单按钮留出空间 */
  }
}
</style> 